package com.sky.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 员工管理
 */
@RestController
@RequestMapping("/admin/employee")
@Slf4j
@Api(tags = "员工相关接口")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("登录接口")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
        log.info("员工登录：{}", employeeLoginDTO);

        Employee employee = employeeService.login(employeeLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();

        return Result.success(employeeLoginVO);
    }

    /**
     * 退出
     *
     * @return
     */
    @ApiOperation("退出接口")
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success();
    }

    /**
     * 保存员工接口
     * @param employeeDTO
     * @return
     */
    @PostMapping
    @ApiOperation("保存员工接口")
    public Result save(@RequestBody EmployeeDTO employeeDTO){
       employeeService.save(employeeDTO);
       return Result.success();
    }


    /**
     * 分页查询接口
     * @param employeePageQueryDTO
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("分页查询接口")
    public Result page(EmployeePageQueryDTO employeePageQueryDTO){
        //查询封装条件
        QueryWrapper<Employee> wrapper = Wrappers.query();
        Page<Employee> employeePage = new Page<>(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        //如果有查询条件则加上
        if (StringUtils.hasText(employeePageQueryDTO.getName())){
            wrapper.like("name",employeePageQueryDTO.getName());
        }
        Page<Employee> page = employeeService.page(employeePage,wrapper);
        return Result.success(page);
    }


    /**
     * 启用或禁用员工账号
     * @param status
     * @param id
     * @return
     */
    @PostMapping("/status/{status}")
    @ApiOperation("启用或禁用员工账号")
    public Result updateStatusById(@PathVariable Integer status,Long id ){
        //使用builder构造器对象设值
        Employee employee = Employee.builder().status(status).id(id).build();
        employeeService.updateById(employee);
        return Result.success();
    }


    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id查询员工")
    public Result<Employee> queryById(@PathVariable Long id){
        Employee employee = employeeService.getById(id);
        //为了安全性，返回的密码为*
        employee.setPassword("*******");
        return Result.success(employee);
    }


    /**
     * 修改员工信息
     * @param employeeDTO
     * @return
     */
    @PutMapping
    @ApiOperation("修改员工信息")
    public Result update(@RequestBody EmployeeDTO employeeDTO){
        Employee employee = Employee.builder()
                .id(employeeDTO.getId())
                .username(employeeDTO.getUsername())
                .name(employeeDTO.getName())
                .phone(employeeDTO.getPhone())
                .sex(employeeDTO.getSex())
                .idNumber(employeeDTO.getIdNumber()).build();
        //当前使用的账号id
        employee.setUpdateUser(BaseContext.getCurrentId());
        //当前的修改时间
        employee.setUpdateTime(LocalDateTime.now());
        boolean result = employeeService.updateById(employee);
        if (result){
            return Result.success();
        }
       return Result.error(MessageConstant.UPDATE_ERROR);
    }
}
